<template>
  <div class="stock_item_page">
    <van-nav-bar :title="stockItem.name" left-arrow @click-left="$router.back()">
      <!--      <template #right>
        <van-icon name="ellipsis" size="18" @click="showStockDetail"/>
      </template>-->
    </van-nav-bar>

    <van-overlay :show="showOverlay" @click="showOverlay = false" class-name="over_layer">
      <van-cell-group class="layer">
        <van-cell value="项目介绍" @click="$router.push('/groupStock/projectIntro')" />
        <van-cell value="公告信息" @click="$router.push('/groupStock/notice')" />
      </van-cell-group>
    </van-overlay>

    <!--<van-row style="margin: 2px 0 10px 0; font-size: 14px" type="flex" justify="end" align="center">
      <van-col offset="16" span="8">
        <span>选择天数11：</span>
        <select>
          <option value="volvo">7</option>
          <option value="saab">30</option>
          <option value="opel">60</option>
          <option value="audi">100</option>
          <option value="audi">其它</option>
        </select>
      </van-col>
    </van-row>-->

    <!-- eCharts容器   -->
    <div ref="stockBox" style="width: 100%; height: 300px"></div>

    <!--  我的股份 和 买卖记录  -->
    <van-tabs
      v-model="currentTab"
      style="margin-top:12px"
      @disabled="onClickDisabled"
      :title-active-color="'#EE0A24'"
      :color="'#EE0A24'"
      @click="handleClickTabs"
    >
      <van-divider
        :style="{
          color: '#323233',
          borderColor: '#BCBCBC',
          padding: '10px 100px 0',
          margin: '0',
          backgroundColor: '#FFFFFF',
          fontWeight: 'bolder'
        }"
      >
        {{ vanTabTitleObj[currentTab] }}
      </van-divider>

      <!-- 我的股份  -->
      <van-tab title="我的股份">
        <van-cell
          title="我的股份"
          size="large"
          center
          :label="
            Number(myStockInfo.amount) > 0
              ? `挂单${myHoldStock.sell || '0'}股，当前持有${myHoldStock.depo}股，共计${myHoldStock.sell * 1 +
                  myHoldStock.depo * 1}股`
              : '尚未持股, 请先申请'
          "
        >
          <template #right-icon>
            <van-button color="#1989FA" size="mini" @click="toSellStock(myStockInfo)">卖出股份</van-button>
          </template>
        </van-cell>
        <van-cell
          center
          title="累计卖出到账"
          :value="myStockInfo.deal ? '￥' + (myStockInfo.deal / 1000).toFixed(3) : '暂无卖出'"
          size="large"
          is-link
          label="点击查看卖出到账记录"
          @click="toTradeRecordsPage(myStockInfo.deal)"
        />
        <van-cell
          center
          title="累计分红"
          :value="myStockInfo.fenhong ? '￥' + myStockInfo.fenhong.toFixed(3) : '暂无分红'"
          size="large"
          is-link
          label="点击查看分红记录"
          @click="toBonusRecords(myStockInfo.fenhong)"
        />
      </van-tab>
      <!--  股份申请审核记录    -->
      <van-tab title="股份申请审核记录">
        <van-cell
          v-for="eachItem in recordOfApplyStockForNextReview"
          :key="eachItem.id"
          :title="eachItem.title"
          is-link
          center
          size="large"
          label="请点击查看"
          @click="toReviewStockRecordPage(eachItem)"
        />
      </van-tab>
      <!-- 买卖记录  -->
      <van-tab title="股份记录" :disabled="Number(myStockInfo.myStockNum) < 0">
        <van-cell
          title="买入记录"
          v-if="allUserInfo.id == SYSTEM_ACCOUNT"
          is-link
          center
          size="large"
          label="点击查看股份记录"
          @click="gobBuyStock"
          :title-style="currentTab === 0 ? {color: '#EE0A24'} : {color: '#1989FA'}"
        />
        <van-cell
          title="派发记录"
          is-link
          center
          size="large"
          label="点击查看派发记录"
          @click="goDistribution"
          :title-style="currentTab === 0 ? {color: '#EE0A24'} : {color: '#1989FA'}"
        />
        <van-cell
          title="卖出记录"
          is-link
          center
          size="large"
          label="点击查看卖出记录"
          @click="toSellRecordPage(myStockInfo.ysdayprice)"
          :title-style="currentTab === 0 ? {color: '#EE0A24'} : {color: '#1989FA'}"
        />
        <van-cell
          title="扣除记录"
          is-link
          center
          size="large"
          label="点击查看扣除记录"
          @click="goDeduct"
          :title-style="currentTab === 0 ? {color: '#EE0A24'} : {color: '#1989FA'}"
        />
      </van-tab>
    </van-tabs>

    <van-divider
      :style="{
        color: '#323233',
        borderColor: '#BCBCBC',
        padding: '10px 100px 0',
        margin: '0',
        backgroundColor: '#FFFFFF',
        fontWeight: 'bolder'
      }"
    >
      股份交易市场
    </van-divider>

    <!-- 股份交易市场  -->
    <div v-if="stockPriceList.length > 0">
      <van-cell v-for="(item, index) in stockPriceList" :key="index">
        <van-row type="flex" justify="space-between">
          <van-col span="10">{{ item.amount + '股' + '/' + '￥' + (item.price / 1000).toFixed(3) }}</van-col>
          <van-col span="10">
            <van-button type="danger" size="small" @click="toBuyStock(item)" style="margin-right: 16px">
              {{ userInfo.id == SYSTEM_ACCOUNT ? '买入' : '申请' }}
            </van-button>
          </van-col>
        </van-row>
      </van-cell>
      <van-pagination
        v-model="pageIndex"
        style="margin: 8px 0"
        :total-items="totalRecord"
        :items-per-page="pageSize"
        force-ellipses
        @change="handleChange"
      />
    </div>

    <van-divider style="margin-top: 80px" v-else>暂无交易</van-divider>
  </div>
</template>

<script>
import {Toast, Dialog, Button} from 'vant'
import echarts from 'echarts'
import {mapGetters} from 'vuex'

import {SYSTEM_ACCOUNT} from '@/constants/systemAccount'

const dayList = [
  {
    id: '1',
    number: '7'
  },
  {
    id: '2',
    number: '30'
  },
  {
    id: '3',
    number: '60'
  },
  {
    id: '4',
    number: '100'
  },
  {
    id: '0',
    number: '其他'
  }
]

const vanTabTitleObj = {
  0: '我的股份',
  1: '股份申请审核记录',
  2: '股份记录'
}

const recordOfApplyStockForNextReview = [
  {
    id: '0',
    title: '我的申请记录'
  },
  {
    id: '1',
    title: '待我审核的申请'
  },
  {
    id: '2',
    title: '我已审核的申请'
  },
  {
    id: '3',
    title: '待集团（后台）审核的申请'
  },
  {
    id: '4',
    title: '集团（后台）已审核的申请'
  }
]

const colors = ['#1989FA', '#EE0A24', '#048D03', '#EE3239']
// 金钱的单位为分
const opening_price = 1000

// 复制官网的options
const options = {
  color: colors,
  grid: {
    left: 46,
    right: 68,
    bottom: 36
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    feature: {
      // 恢复默认按钮
      restore: {show: true}
    }
  },
  legend: {
    data: ['股价', '分红', '股价走势', '分红走势']
  },
  dataZoom: [
    //1.横向使用滚动条
    {
      type: 'slider', //有单独的滑动条，用户在滑动条上进行缩放或漫游。inside是直接可以是在内部拖动显示
      show: true, //是否显示 组件。如果设置为 false，不会显示，但是数据过滤的功能还存在。
      start: 10, //数据窗口范围的起始百分比0-100
      end: 100, //数据窗口范围的结束百分比0-100
      xAxisIndex: [0], // 此处表示控制第一个xAxis，设置 dataZoom-slider 组件控制的 x轴 可是已数组[0,2]表示控制第一，三个；xAxisIndex: 2 ，表示控制第二个。yAxisIndex属性同理
      bottom: -12 //距离底部的距离
    },
    //2.在内部可以横向拖动
    {
      type: 'inside', // 内置于坐标系中
      start: 10,
      end: 100,
      xAxisIndex: [0]
    }

    //3.纵向使用滚动条
    /*{
        type: 'slider',
        // show: true,
        yAxisIndex: [0],//设置组件控制的y轴
        left: '93%',//距离左侧的距离 可以使百分比，也可以是像素 left: '30'（30像素）
        start: 29,
        end: 36
      },
      //4.在内部可以纵向拖动
      {
        type: 'inside',
        yAxisIndex: [0],
        start: 29,
        end: 36
      }*/
  ],
  xAxis: [
    {
      type: 'category',
      data: [],
      scale: true,
      axisPointer: {
        // type: 'shadow',
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: '股份价/￥',
      scale: true,
      splitLine: {
        show: true
      },
      axisLine: {
        lineStyle: {
          color: colors[0]
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    },
    {
      type: 'value',
      name: '分红价/￥',
      scale: true,
      splitLine: {
        show: true
      },
      axisLine: {
        lineStyle: {
          color: colors[1]
        }
      },
      axisLabel: {
        formatter: '{value}'
      }
    }
  ],
  series: [
    {
      name: '股价',
      type: 'bar',
      data: []
    },
    {
      name: '分红',
      type: 'bar',
      yAxisIndex: 1,
      data: []
    },
    {
      name: '股价走势',
      type: 'line',
      data: []
    },
    {
      name: '分红走势',
      type: 'line',
      yAxisIndex: 1,
      data: []
    }
  ]
}

const timer = 60000

export default {
  name: 'market_page',
  data() {
    return {
      SYSTEM_ACCOUNT,
      showTel: false,
      vanTabTitleObj,
      recordOfApplyStockForNextReview,
      distributionData: [],
      showOverlay: false,
      isShowMyStock: false,
      currentTab: 0,
      dayList,
      // 买入
      buyCount: '',
      buyPrice: '',
      buyTotalPrice: '',
      // 卖出
      sellCount: '',
      sellPrice: '',
      sellTotalPrice: '',

      // 交易密码
      tradePassword: '',
      myStockInfo: {},
      stockPriceList: [],
      // eCharts 需要的数据

      pageIndex: 1,
      pageSize: 20,
      totalRecord: 0,
      // 当日开盘价
      openingPrice: opening_price,
      // 传递过来的对象
      stockItem: {},
      activeTab: 1,
      myHoldStock: {},
      userInfo: ''
    }
  },
  components: {},

  created() {
    this.currentTab = sessionStorage.getItem('group_activatedTabs') * 1
    this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    // console.log('userInfo');
    // console.log(this.userInfo);
    // console.log('userInfo');
    const item = this.$route.params.item || localStorage.getItem('stockItem') || this.$route.query.item
    // 若有obj, 则保存
    if (item) {
      if (this.$route.params.item || this.$route.query.item) {
        localStorage.setItem('stockItem', item)
      }
      this.stockItem = JSON.parse(localStorage.getItem('stockItem'))
    } else {
      this.$router.push('/groupStock')
      localStorage.removeItem('stockItem')
    }
  },

  mounted() {
    // 第一步：初始化echarts
    this.myEcharts = echarts.init(this.$refs.stockBox)
    // 第二步： 设置options对象
    this.myEcharts.setOption(options)

    if (this.stockItem.id) {
      // 先执行一次
      this._initPage()
    }

    if (this.stockItem.id) {
      this.timeName = setInterval(() => {
        this._initPage()
      }, timer)
    }
  },
  methods: {
    goDeduct() {
      // 注: 派发是buyRecords
      this.$router.push({
        name: 'deductRecords'
        // params: {
        //   obj: this.needParams
        // }
      })
    },
    _initPage() {
      // 某个股份的详情
      this.$api.stock.reqStockDetail(this.stockItem.id).then(res => {
        if (res.code === 200) {
          const resultData = res.data.myinfo
          const initDayPrice = res.data.quota.ysdayprice
          // 对象增加一个新属性
          //  object.setAttribute(attribute, value)
          resultData.ysdayprice = initDayPrice
          this.myStockInfo = resultData
        }
      })

      // 股份交易市场的数据
      const params_market = {
        id: this.stockItem.id,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      this.$api.stock.reqAllUserStockSell(params_market).then(res => {
        if (res.code === 200) {
          this.stockPriceList = res.data.items
          this.totalRecord = res.data.total
        }
      })

      // 当前的持有股票
      this.$api.stock.reqMyHoldStock(this.stockItem.id).then(res => {
        if (res.code === 200) {
          this.myHoldStock = res.data
        }
      })

      // Echart图需要的数据
      this.needParams = {
        id: this.stockItem.id,
        top: '1000',
      }
      this.$api.stock.reqMyEchartData(this.needParams).then(res => {
        if (res.code === 200) {
          // 日期
          options.xAxis[0].data = res.data.dates || []
          // 股份价格
          options.series[0].data = res.data.prices || []
          options.series[2].data = res.data.prices || []

          // 股份最大、最小值
          // this.eChartsStockMax = Math.max( ...(res.data.prices))
          // this.eChartsStockMin = Math.min( ...(res.data.prices))
          // console.log('柱状图的最大、小', this.eChartsStockMax, this.eChartsStockMin)

          // 分红价格
          options.series[1].data = res.data.bonus || []
          options.series[3].data = res.data.bonus || []

          // 分红最大、最小值
          // this.eChartsBonusMax = Math.max( ...(res.data.bonus))
          // this.eChartsBonusMin = Math.min( ...(res.data.bonus))
          // console.log('折线图的最大、小', this.eChartsBonusMax, this.eChartsBonusMin)

          // 需再设置options
          this.myEcharts.setOption(options)
        }
      })
    },

    _toGetStockItemAndUserInfo() {
      // 李进 添加
      this.userInfo = JSON.parse(localStorage.getItem('userInfo'))

      const item = this.$route.params.item || localStorage.getItem('stockItem') || this.$route.query.item
      // 若有obj, 则保存
      if (item) {
        if (this.$route.params.item || this.$route.query.item) {
          localStorage.setItem('stockItem', item)
        }
        this.stockItem = JSON.parse(localStorage.getItem('stockItem'))
      } else {
        this.$router.push('/groupStock')
        localStorage.removeItem('stockItem')
      }
    },

    goDistribution() {
      // 注: 派发是buyRecords
      this.$router.push({
        name: 'buyRecords'
        // params: {
        //   obj: this.needParams
        // }
      })
    },
    // 买入记录
    gobBuyStock() {
      this.$router.push({
        name: 'buyHistory'
      })
    },

    showStockDetail() {
      this.showOverlay = true
    },
    // 去买入或去申请
    toBuyStock(item) {
      if (this.allUserInfo.certification_state === 2) {
        if (this.userInfo.id == SYSTEM_ACCOUNT) {
          // 联系平台账号，admin
          this.$router.push({
            name: 'buyStock',
            params: {
              obj: JSON.stringify(item)
            }
          })
        } else {
          // 平台账号(即: 一般人员, 只能申请股份);
          // console.log('申请股份', item);

          const eachStockDetail = {
            ...item,
            stockName: this.stockItem.name
          }
          this.$router.push({
            name: 'applyStock',
            query: {
              eachStockObj: JSON.stringify(eachStockDetail)
            }
          })
        }
      } else {
        Dialog.confirm({
          title: '个人认证还没完成！！',
          message: '当前操作需完成个人认证！你当前还没有完成个人认证，请点击去个人认证。',
          messageAlign: 'left',
          confirmButtonText: '前往个人认证'
        })
          .then(() => {
            this.$router.push('/personalAuth')
          })
          .catch(() => {
            // on cancel
          })
      }
    },

    handleClickTabs(name, title) {
      // console.log(name,title)
      sessionStorage.setItem('group_activatedTabs', name)
    },

    // 去卖出股份
    toSellStock(myStockInfo) {
      if (this.myStockInfo.amount && Number(this.myStockInfo.amount) > 0) {
        this.$router.push({
          name: 'sellStock',
          params: {
            myStockInfo: JSON.stringify(myStockInfo)
          }
        })
      } else {
        Toast('尚未持股，无法卖出。请先申请股份！')
      }
    },
    // 去分红页
    toBonusRecords(value) {
      if (value && value * 1 > 0) {
        this.$router.push({
          name: 'bonusRecords',
          params: {
            needBonusData: value
          }
        })
      } else {
        Toast('暂无分红，请先申请股份！或着您持股不超过24小时。请在分红后查看。')
      }
    },
    // 去卖出到账页
    toTradeRecordsPage(value) {
      if (value && value * 1 > 0) {
        this.$router.push('/groupStock/tradeRecords')
      } else {
        Toast('尚未卖出到账！')
      }
    },

    toReviewStockRecordPage(eachItem) {
      this.$router.push({
        name: 'reviewStockRecord',
        query: {
          dataObj: JSON.stringify({
            eachItem,
            stockItem: this.stockItem
          })
        }
      })
    },
    onClickDisabled() {
      Toast('尚未持股，没有买卖记录')
    },

    toSellRecordPage(value) {
      this.$router.push({
        name: 'sellRecords',
        params: {
          price: value
        }
      })
    },

    handleChange(value) {
      const params = {
        id: this.stockItem.id,
        pageIndex: value,
        pageSize: this.pageSize
      }
      this.$api.stock.reqAllUserStockSell(params).then(res => {
        if (res.code === 200) {
          this.stockPriceList = res.data.items
          this.totalRecord = res.data.total
        }
      })
    }
  },
  computed: {
    ...mapGetters(['allUserInfo'])
  },

  beforeDestroy() {
    // 清除定时器
    clearInterval(this.timeName)
    clearInterval(this.timeName_2)
  },

  // 生命周期钩子函数
  destroyed() {
    // 日期
    options.xAxis[0].data = []
    // 股份价格
    options.series[0].data = []
    options.series[2].data = []
    // 分红价格
    options.series[1].data = []
    options.series[3].data = []
    // 需再设置options
    this.myEcharts.setOption(options)
  },

  activated() {
    this._toGetStockItemAndUserInfo()

    if (this.stockItem.id) {
      console.log('缓存组件---进入时---执行')
      this.timeName_2 = setInterval(() => {
        this._initPage()
      }, timer)
    }
  },

  deactivated() {
    // console.log('缓存组件离开时---执行')
    // 清除定时器: 避免缓存组件内存泄漏
    clearInterval(this.timeName)
    clearInterval(this.timeName_2)
  }
}
</script>

<style lang="scss" scoped>
.stock_item_page {
  width: 100%;
  box-sizing: border-box;
  .over_layer {
    margin-top: 46px;
    height: 100%;
    .layer {
      width: 40%;
      font-size: 14px;
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: auto;
  padding: 15px;
  height: 120px;
  background-color: #fff;
  border-radius: 10px;
  .copy {
    font-size: 16px;
    font-weight: bold;
  }
  .copy_btn {
    margin: 10px auto;
    float: right;
  }
}

.van-cell__value--alone {
  text-align: center !important;
}
</style>
